import 'package:convergence_media/features/api/apis/circle_csavs_api.dart';
import 'package:convergence_media/features/app/repository/app_config_repository.dart';
import 'package:convergence_media/features/config/errors/login_errors.dart';
import 'package:convergence_media/features/user/repositories/token_repository.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'circle_auth_service.g.dart';

@riverpod
CircleAuthService circleAuthService(CircleAuthServiceRef ref) =>
    CircleAuthService(
      circleCsavsApi: ref.watch(circleCsavsApiProvider),
      tokenRepository: ref.watch(tokenRepositoryProvider),
      appConfigRepository: ref.watch(appConfigRepositoryProvider),
    );

/// {@template circle_auth_service}
/// 圈子鉴权服务
/// {@endtemplate}
class CircleAuthService {
  /// {@macro circle_auth_service}
  CircleAuthService({
    required AppConfigRepository appConfigRepository,
    required CircleCsavsApi circleCsavsApi,
    required TokenRepository tokenRepository,
  })  : _appConfigRepository = appConfigRepository,
        _postCsavsApi = circleCsavsApi,
        _tokenRepository = tokenRepository;

  final TokenRepository _tokenRepository;
  final CircleCsavsApi _postCsavsApi;
  final AppConfigRepository _appConfigRepository;

  /// 圈子的登录，返回布尔值标识是否成功，抛出 NotLoginException 跳转登录
  Future<void> login() async {
    final currentHashId = _appConfigRepository.getCurrentHashId();
    if (currentHashId == null) {
      throw AuthException.withoutToken();
    }
    final mainToken = await _tokenRepository.getMainToken(currentHashId);
    if (mainToken == null) {
      throw AuthException.withoutToken();
    }
    final loginResponse = await _postCsavsApi.postLoginTokenLogin(mainToken);

    // 存储圈子的 token
    await _tokenRepository.putCircleToken(
      currentHashId,
      loginResponse.data.loginToken,
    );
  }
}
